#encoding=utf8
'''
Created on May 12, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple

from suit.widgets import SuitDateWidget

from app_info.models import APP_STORE, AppVersion
from core.widgets import CustomCheckboxSelectMultiple
from prd_order.models import ProductionOrder, Project, PROCEDURE_NAMES,\
    Procedure, JOB_FAMILY_MAP
from utils import api_call
import settings


class ProductionOrderAdminForm(forms.ModelForm):

    app_store = forms.MultipleChoiceField(required=False,
        widget=CustomCheckboxSelectMultiple, choices=APP_STORE,
        label='App Store')

    def __init__(self, *args, **kwargs):
        super(ProductionOrderAdminForm, self).__init__(*args, **kwargs)
        if self.instance.pk is not None:
            division = self.instance.to
            self.fields['assign_team'].queryset = division.productionteam_set.all()

    class Meta:
        model = ProductionOrder
        widgets = {'date_issued': SuitDateWidget,
                   'date_received': SuitDateWidget,
                   'required_release_date': SuitDateWidget,
                   'confirmed_date': SuitDateWidget}

    def clean_app_store(self):
        store = self.cleaned_data.get('app_store')
        return store or ""


class ProjectAdminForm(forms.ModelForm):

    error_messages = {'required': 'This field is required.'}

    proce = forms.MultipleChoiceField(required=False,
        widget=CustomCheckboxSelectMultiple, choices=PROCEDURE_NAMES,
        label='Procedure')

    def __init__(self, *args, **kwargs):
        super(ProjectAdminForm, self).__init__(*args, **kwargs)
        self.fields['tasks'].widget = FilteredSelectMultiple('Production Tasks',
            False, {"style": "height: 300px;"})
        if self.instance and self.instance.pk and self.instance.pjm:
            self.fields['tasks'].queryset = AppVersion.objects.filter(
                owner=self.instance.pjm.pk,
                status__in=['I', 'O']
                )

    def clean_studio(self):
        studio = self.cleaned_data.get('studio')
        if not studio:
            raise forms.ValidationError(self.error_messages['required'])
        return studio

    class Meta:
        model = Project
        widgets = {'plan_start': SuitDateWidget, 'plan_end': SuitDateWidget,
                   'real_start': SuitDateWidget}


class ProcedureForm(forms.ModelForm):

    staffing = forms.MultipleChoiceField(required=False, label='Staffing')

    def __init__(self, *args, **kwargs):
        super(ProcedureForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            choices = ()
            fid = JOB_FAMILY_MAP.get(self.instance.name)
            data = api_call('%s%s' % (settings.TMS_DOMAIN, settings.TMS_GET_STAFFING),
                {'jobfamily': fid})
            if data.get('code') == 1:
                list = []
                staffs = data['staffs']
                for s in staffs:
                    list += s['list']
                choices += tuple([('%s - %s' % (x['EmployeeCode'], x['ChineseName']),
                                  '%s - %s' % (x['EmployeeCode'], x['ChineseName']))\
                                 for x in list])
                self.fields['staffing'].choices = choices
            if self.instance.staffing:
                initial = self.instance.staffing.split(',')
                # 'self.fields['staffing'].initial = initial' does not work!!
                self.initial['staffing'] = initial

    def clean_staffing(self):
        staffing = self.cleaned_data.get('staffing')
        if staffing:
            staffing = ','.join(staffing)
        return staffing or None

    class Meta:
        model = Procedure

    class Media:
        js = ('chosen/chosen.jquery.min.js',
              'base/js/custom_procedure.js',
            )
        css = {'all': ('chosen/chosen.min.css',)}
